/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.support;

import java.io.IOException;
import java.io.ObjectInputStream;

import org.aopalliance.aop.Advice;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Abstract BeanFactory-based PointcutAdvisor that allows for any Advice
 * to be configured as reference to an Advice bean in a BeanFactory.
 *
 * <p>Specifying the name of an advice bean instead of the advice object itself
 * (if running within a BeanFactory) increases loose coupling at initialization time,
 * in order to not initialize the advice object until the pointcut actually matches.
 *
 * @author Juergen Hoeller
 * @since 2.0.2
 * @see #setAdviceBeanName
 * @see DefaultBeanFactoryPointcutAdvisor
 */
/*
1. 总结
AbstractBeanFactoryPointcutAdvisor 是 Spring AOP 框架中的一个抽象类，用于支持基于 BeanFactory 的 PointcutAdvisor。
	它允许将 Advice 配置为对 BeanFactory 中某个 Advice Bean 的引用，实现松耦合和延迟初始化。
	提供了对 Advice 的缓存机制，确保在生命周期内只获取一次 Advice 实例。
2. 内部成员说明
	字段
		adviceBeanName: 存储 Advice Bean 的名称，用于从 BeanFactory 中获取 Advice 实例。
		beanFactory: 引用当前的 BeanFactory，用于解析 Advice Bean。
		advice: 缓存获取到的 Advice 实例，避免重复获取。
		adviceMonitor: 用于同步访问 advice 字段的锁对象。
	方法
		setAdviceBeanName(String adviceBeanName): 设置 Advice Bean 的名称。
		getAdviceBeanName(): 获取 Advice Bean 的名称。
		setBeanFactory(BeanFactory beanFactory): 设置 BeanFactory，并重置 adviceMonitor。
		setAdvice(Advice advice): 直接设置 Advice 实例，跳过懒加载。
		getAdvice(): 获取 Advice 实例，实现懒加载和缓存。
		toString(): 返回该 Advisor 的字符串表示。
		readObject(ObjectInputStream ois): 序列化反序列化时的回调方法，用于初始化 transient 字段。
3. 类关系结构
Advisor (interface)
└── PointcutAdvisor (interface)
    └── AbstractPointcutAdvisor (abstract class)	抽象基类，实现了 PointcutAdvisor 接口，提供了基本的 Pointcut 支持。
        └── AbstractBeanFactoryPointcutAdvisor (abstract class)
            ├── DefaultBeanFactoryPointcutAdvisor (class)	具体实现类，通常用于配置通用的 PointcutAdvisor。
            ├── BeanFactoryTransactionAttributeSourceAdvisor (class)	用于事务管理的 Advisor，结合了事务属性源。
            ├── BeanFactoryCacheOperationSourceAdvisor (class)	用于缓存操作的 Advisor，支持缓存注解。
            └── BeanFactoryJCacheOperationSourceAdvisor (class)	用于 JCache 规范的缓存操作 Advisor。
相关类和接口关系说明
	Advisor: 最顶层接口，定义了 AOP 顾问的基本契约。
	PointcutAdvisor: 继承自 Advisor，增加了 Pointcut 的概念，用于定义切点。
	AbstractPointcutAdvisor: 抽象基类，实现了 PointcutAdvisor 接口，提供了基本的 Pointcut 支持。
	DefaultBeanFactoryPointcutAdvisor: 具体实现类，通常用于配置通用的 PointcutAdvisor。
	BeanFactoryTransactionAttributeSourceAdvisor: 用于事务管理的 Advisor，结合了事务属性源。
	BeanFactoryCacheOperationSourceAdvisor: 用于缓存操作的 Advisor，支持缓存注解。
	BeanFactoryJCacheOperationSourceAdvisor: 用于 JCache 规范的缓存操作 Advisor。
4. 使用场景
在 Spring AOP 中配置基于 BeanFactory 的 PointcutAdvisor。
实现松耦合的 Advice 配置，避免在初始化时立即创建 Advice 实例。
支持事务、缓存等横切关注点的 AOP 配置。
在需要延迟初始化 Advice 的场景中使用。
5. 实际代码应用示例
// 配置一个基于 BeanFactory 的 PointcutAdvisor
@Configuration
public class AopConfig {

    @Bean
    public PointcutAdvisor myAdvisor() {
        DefaultBeanFactoryPointcutAdvisor advisor = new DefaultBeanFactoryPointcutAdvisor();
        advisor.setPointcut(new JdkRegexpMethodPointcut().setPatterns(".*Service.*"));
        advisor.setAdviceBeanName("myAdviceBean");
        return advisor;
    }

    @Bean
    public Advice myAdviceBean() {
        return new MethodBeforeAdvice() {
            @Override
            public void before(Method method, Object[] args, Object target) throws Throwable {
                System.out.println("Before method: " + method.getName());
            }
        };
    }
}

 */
@SuppressWarnings("serial")
public abstract class AbstractBeanFactoryPointcutAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {

	@Nullable
	private String adviceBeanName;

	@Nullable
	private BeanFactory beanFactory;

	@Nullable
	private transient volatile Advice advice;

	private transient volatile Object adviceMonitor = new Object();


	/**
	 * Specify the name of the advice bean that this advisor should refer to.
	 * <p>An instance of the specified bean will be obtained on first access
	 * of this advisor's advice. This advisor will only ever obtain at most one
	 * single instance of the advice bean, caching the instance for the lifetime
	 * of the advisor.
	 * @see #getAdvice()
	 */
	public void setAdviceBeanName(@Nullable String adviceBeanName) {
		this.adviceBeanName = adviceBeanName;
	}

	/**
	 * Return the name of the advice bean that this advisor refers to, if any.
	 */
	@Nullable
	public String getAdviceBeanName() {
		return this.adviceBeanName;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
		resetAdviceMonitor();
	}

	private void resetAdviceMonitor() {
		if (this.beanFactory instanceof ConfigurableBeanFactory) {
			this.adviceMonitor = ((ConfigurableBeanFactory) this.beanFactory).getSingletonMutex();
		}
		else {
			this.adviceMonitor = new Object();
		}
	}

	/**
	 * Specify a particular instance of the target advice directly,
	 * avoiding lazy resolution in {@link #getAdvice()}.
	 * @since 3.1
	 */
	public void setAdvice(Advice advice) {
		synchronized (this.adviceMonitor) {
			this.advice = advice;
		}
	}

	@Override
	public Advice getAdvice() {
		Advice advice = this.advice;
		if (advice != null) {
			return advice;
		}

		Assert.state(this.adviceBeanName != null, "'adviceBeanName' must be specified");
		Assert.state(this.beanFactory != null, "BeanFactory must be set to resolve 'adviceBeanName'");

		if (this.beanFactory.isSingleton(this.adviceBeanName)) {
			// Rely on singleton semantics provided by the factory.
			advice = this.beanFactory.getBean(this.adviceBeanName, Advice.class);
			this.advice = advice;
			return advice;
		}
		else {
			// No singleton guarantees from the factory -> let's lock locally but
			// reuse the factory's singleton lock, just in case a lazy dependency
			// of our advice bean happens to trigger the singleton lock implicitly...
			synchronized (this.adviceMonitor) {
				advice = this.advice;
				if (advice == null) {
					advice = this.beanFactory.getBean(this.adviceBeanName, Advice.class);
					this.advice = advice;
				}
				return advice;
			}
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(getClass().getName());
		sb.append(": advice ");
		if (this.adviceBeanName != null) {
			sb.append("bean '").append(this.adviceBeanName).append('\'');
		}
		else {
			sb.append(this.advice);
		}
		return sb.toString();
	}


	//---------------------------------------------------------------------
	// Serialization support
	//---------------------------------------------------------------------

	private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
		// Rely on default serialization, just initialize state after deserialization.
		ois.defaultReadObject();

		// Initialize transient fields.
		resetAdviceMonitor();
	}

}
